package leetcodev1.字符串;

import leetcodev1.链表.Solution;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class LeetCode20 {
    Map<Character, Character> dict = new HashMap<Character, Character>() {{
        put('(', ')');
        put('[', ']');
        put('{', '}');
    }};

    //1.使用栈辅助
    //2.使用对撞指针进行 不行，题没看对
    public boolean isValid(String s) {
        if (s.length() % 2 != 0) {
            return false;
        }

        int left = 0, right = s.length() - 1, n = s.length();
        while (left < right) {
            if (!dict.containsKey(s.charAt(left))) {
                return false;
            }

            if (dict.get(s.charAt(left)) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }

    //使用栈
    public boolean isValid1(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
